package com.fivestyle.controller;


import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fivestyle.common.lang.Result;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fivestyle.common.result.R;
import com.fivestyle.common.tool.JwtUtils;
import com.fivestyle.entity.Orders;
import com.fivestyle.service.OrderService;
import io.swagger.annotations.ApiOperation;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.Arrays;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 张代钊
 * @since 2021-08-04
 */
@RestController
@RequestMapping("/onlinebook/order")
public class OrderController extends BaseController{

    @Autowired
    private OrderService orderService;

//    更新用户的收货地址
    @ApiOperation(value = "更新用户的收货地址",notes = "传入userId、addr键值对，更新用户的收货地址")
    @PutMapping("updateAddr")
    public R updateAddr(@RequestBody String json){
        return orderService.updateAddr(json);
    }

//    查找该用户的全部订单（支付成功的，未支付的）
    @ApiOperation(value = "查询全部订单",notes = "通过userId查找该用户的全部订单（支付成功的，未支付的）")
    @GetMapping("getAllOrder/{userId}")
    public R getAllOrder(@PathVariable String userId){
        return orderService.getAllOrder(userId);
    }

//    增加减少数量时，更新 购物车里的单个订单的价格和书本数量
    @ApiOperation(value = "修改购物车",notes = "购物车发生变动时，增加减少数量时，更新 购物车里的单个订单的价格和书本数量")
    @Transactional
    @PutMapping("cntChanged")
    public R cntChanged(@RequestBody Orders orders){
        orders.setMoneyTotal(orders.getBookPrice().multiply(new BigDecimal(orders.getBookCount())));
        orderService.saveOrUpdate(orders);
        return R.ok().data("order",orders).message("更新单个订单记录成功！");
    }

//    删除该购物车里的该条商品记录
    @ApiOperation(value = "删除商品",notes = "删除该购物车里的该条商品记录")
    @Transactional
    @DeleteMapping("removeOrder")
    public R removeOrder(@RequestBody Orders orders){
        orderService.removeById(orders.getId());
        return R.ok().message("删除单条订单记录成功！");
    }


//    添加一个新订单到购物车
    @ApiOperation(value = "添加商品到购物车",notes = "添加一个新订单到购物车")
    @PostMapping("addSomeToBuy/{bookId}/{userId}")
    public R addSomeToBuy(@PathVariable String bookId, @PathVariable String userId){
      return orderService.addSomeToBuy(bookId,userId);
    }

//    根据订单id查询订单信息
    @ApiOperation(value = "查询订单",notes = "根据订单id查询订单信息")
    @GetMapping("getOrderInfo/{orderId}")
    public R getOrderInfo(@PathVariable String orderId) {
        QueryWrapper<Orders> wrapper = new QueryWrapper<>();
        wrapper.eq("id",orderId);
        Orders one = orderService.getOne(wrapper);
        if (one != null){
            return R.ok().data("order",one);
        }else {
            return R.error().message("没有查询到该订单！");
        }
    }

//    分页查询该用户的购物车（未支付的商品）
    @ApiOperation(value = "获取购物车",notes = "分页查询该用户的购物车（未支付的商品）")
    @GetMapping("getOrderList/{current}/{size}")
    public R getOrderList(@PathVariable Long current, @PathVariable Long size,HttpServletRequest request){
        return orderService.getOrderList(current,size, JwtUtils.getMemberIdByJwtToken(request));
    }


    /**
     * 后台管理
     */

    @Autowired
    BCryptPasswordEncoder passwordEncoder;

    @GetMapping("/info/{id}")
    @PreAuthorize("hasAuthority('web:order:list')")
    public Result info(@PathVariable("id") String id) {
        Orders orders = orderService.getById(id);
        Assert.notNull(orders, "找不到该订单");
        return Result.succ(orders);
    }

    @GetMapping("/list")
    @PreAuthorize("hasAuthority('web:order:list')")
    public Result list(String userName) {
        Page<Orders> pageData=orderService.page(getPage(),new QueryWrapper<Orders>()
                .like(StrUtil.isNotBlank(userName), "user_name", userName));
        return Result.succ(pageData);
    }

    @Transactional
    @PostMapping("/delete")
    @PreAuthorize("hasAuthority('web:order:delete')")
    public Result delete(@RequestBody String[] ids) {
        orderService.removeByIds(Arrays.asList(ids));
        return Result.succ("");
    }
}

